import axios from 'axios'

// 创建 axios 实例
const service = axios.create({
  baseURL: 'http://localhost:8083/',
  timeout: 10000 // 请求超时时间
})

// 请求拦截器 - 添加 token
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('jwt')
    if (token) {
      config.headers['token'] = token
    }
    return config
  },
  error => {
    console.log('请求错误:', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response
    
    if (res.jwt) {
      localStorage.setItem('jwt', res.jwt)
    }
    
    return res
  },
  async error => {
    const router = await import('@/router').default
    
    if (error.response) {
      const { status, data } = error.response
      
      // token 过期或无效
      if (status === 401 || (data && (data.code === 49 || data.code === 4001))) {
        localStorage.clear()
        router.replace('/login')
        
        if (data && data.msg) {
          alert(data.msg)
        } else {
          alert('登录已过期，请重新登录')
        }
      }
      
      // 权限不足
      if (status === 4002) {
        alert('权限不足')
      }
    }
    
    return Promise.reject(error)
  }
)

export default service